package com.enqualcomm.kids.mvp;

import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.enqualcomm.kids.component.MyApplication;
import com.enqualcomm.kids.network.SocketRequest;

import common.utils.NetUtil;

/**
 * Created by yinzhiqun on 2015/9/22.
 *
 */
public class NetworkModel {
    private RequestQueue httpRequestQueue;
    private RequestQueue socketRequestQueue;

    /**
     * 联网获取数据，可能出现的异常有：
     * 1.NoConnectionError，联网之前会检查网络连接
     * 2.TimeoutError,Socket连接超时
     * 3.NetworkError,IO异常
     * 4.ParseError,解析出错
     * 5.VolleyError,未知异常
     *
     * @param request
     */
    public void loadDataFromServer(Request request){
        if (NetUtil.checkNet(MyApplication.getInstance())){
            if (httpRequestQueue==null){
                httpRequestQueue = MyApplication.getInstance().getHttpRequestQueue();
            }
            request.setTag(this);//设置tag，退出时取消
            httpRequestQueue.add(request);
        }else{//没有网络连接
            request.deliverError(new NoConnectionError());
        }
    }

    public void loadDataFromServer(SocketRequest request){
        if (NetUtil.checkNet(MyApplication.getInstance())){
            if (socketRequestQueue==null){
                socketRequestQueue = MyApplication.getInstance().getSocketRequestQueue();
            }
            request.setTag(this);//设置tag，退出时取消
            socketRequestQueue.add(request);
        }else{//没有网络连接
            request.deliverError(new NoConnectionError());
        }
    }

    public void onStop() {
        if (httpRequestQueue!=null){//退出时，取消所有的请求
            httpRequestQueue.cancelAll(this);
        }
        if (socketRequestQueue!=null){
            socketRequestQueue.cancelAll(this);
        }
    }
}
